package cn.didi.feidi.androidorder.fragment.personal;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.google.gson.reflect.TypeToken;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.personal.PersonChangeFeidiNumOnceActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonChangeNameActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonChangePasswordActivity;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import de.hdodenhof.circleimageview.CircleImageView;

public class PersonMessageFragment extends FeidiBaseFragment implements TakePhoto.TakeResultListener, InvokeListener {

    private static final String TAG = "PersonMessageFragment";
    //    上传图片的管理对象
    Configuration configuration = new Configuration.Builder().zone(AutoZone.autoZone).build();
    UploadManager uploadManager = new UploadManager(configuration);
    //    takePhoto
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径
    private InvokeParam invokeParam;
    //    上传头像后得到的fileKey
    private String iconFileKey;
    //    七牛云上传凭证
    private String qiNiuYunToken;
    private LinearLayout personIcon_ll;
    private LinearLayout personName_ll;
    private LinearLayout personFeidiNumber_ll;
    private LinearLayout changePassword_ll;
    private TextView personName;
    private TextView feidiNumber;
    private CircleImageView personIcon;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonMessageFragment newInstance(Bundle bundle) {
        PersonMessageFragment fragment = new PersonMessageFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_message, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        personIcon_ll = (LinearLayout) rootView.findViewById(R.id.person_message_person_icon_ll);
        personName_ll = (LinearLayout) rootView.findViewById(R.id.person_message_person_name_ll);
        personFeidiNumber_ll = (LinearLayout) rootView.findViewById(R.id.person_message_person_feidi_number_ll);
        changePassword_ll = (LinearLayout) rootView.findViewById(R.id.person_message_change_password_ll);

        personName = (TextView) rootView.findViewById(R.id.person_message_person_name);
        feidiNumber = (TextView) rootView.findViewById(R.id.person_message_person_feidi_number);
        personIcon = (CircleImageView) rootView.findViewById(R.id.person_message_person_icon);
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        //  : 2017/8/3 初始化 personName  feidiNumber   personIcon的值
        personName.setText(UserManager.getName());
        feidiNumber.setText(UserManager.getFeidiAccount());
        if (UserManager.getFeidiAccountStatus()) {
            personFeidiNumber_ll.setClickable(false);
        }
        Glide.with(mActivity).load(UserManager.getHeadPortrait()).asBitmap().placeholder(R.drawable.person_center_person_default_icon).centerCrop().into(new BitmapImageViewTarget(personIcon) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(getResources(), resource);
                circularBitmapDrawable.setCircular(true);
                personIcon.setImageDrawable(circularBitmapDrawable);
            }
        });
    }

    @Override
    protected void addListener() {
        personIcon_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getQiNiuYunToken();
            }
        });
        personName_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonChangeNameActivity.class);
                startActivity(intent);
            }
        });
        personFeidiNumber_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  : 2017/8/3 判断飞滴号是否可修改(只可修改一次)
                if (!UserManager.getFeidiAccountStatus()) {
                    Intent intent = new Intent(getContext(), PersonChangeFeidiNumOnceActivity.class);
                    startActivity(intent);
                }
            }
        });
        changePassword_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonChangePasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    private void choosePersonIconFromDialog() {

        //获取TakePhoto实例
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setWithOwnCrop(true).setOutputX(180).setOutputY(180).create();
        //设置压缩参数
        compressConfig = new CompressConfig.Builder().enableQualityCompress(false).setMaxSize(30 * 1024).create();
        takePhoto.onEnableCompress(compressConfig, false);  //设置为需要压缩

        String[] operateSets = new String[]{"相册获取", "拍照获取"};
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setItems(operateSets, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            imageUri = getImageCropUri();
                            //从相册中选取图片并裁剪
                            takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                        }
                        if (which == 1) {
                            imageUri = getImageCropUri();
                            //拍照并裁剪
                            takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                        }
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    @Override
    public void takeSuccess(TResult result) {
        String iconPath = result.getImage().getOriginalPath();
        //上传图片
        new sendPhotoTask().execute(iconPath);
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getTakePhoto().onCreate(savedInstanceState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    private void getQiNiuYunToken() {
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());

        executeRequest(new AppActionRequest<>(Api.UPDATE_QI_NIU_YUN_TOKEN, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                qiNiuYunToken = data;
                choosePersonIconFromDialog();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        //不存在当前用户
                        break;
                    case ErrorEvent.WRONG_PASSWORD:
                        //密码错误
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("账号名为手机号");
                        break;
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }

    private void uploadIconInServer() {
        //进行登陆
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("imgKey", iconFileKey);

        executeRequest(new AppActionRequest<>(Api.UPDATE_PERSON_ICON, params,
                new TypeToken<ApiResponse>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                makeToast("头像上传成功");
                UserManager.setHeadPortrait(data);
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        //不存在当前用户
                        break;
                    case ErrorEvent.WRONG_PASSWORD:
                        //密码错误
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("账号名为手机号");
                        break;
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }

    private class sendPhotoTask extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... params) {

            String data = params[0];
            String key = null;

            uploadManager.put(data, key, qiNiuYunToken,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Log.i("qiniu", "Upload Success");
                                try {
                                    iconFileKey = res.getString("key");
                                    uploadIconInServer();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
//                                    saveImageKey[flag_photo] = res.getString("key");
                            } else {
                                Log.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            }
                            Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                        }
                    }, null);
            return null;
        }
    }
}
